<!--编号规则-->
<template>
    <el-form :model="codeform" ref="coderef" :inline="true" style="text-align: left;">
        <el-form-item label="目标表单:" prop="name">
            <el-input placeholder="请输入目标名称" v-model="codeform.name"></el-input>
        </el-form-item>
        <el-form-item label="编号前缀:" prop="prefix">
            <el-input placeholder="请输入" v-model="codeform.prefix"></el-input>
        </el-form-item>
        <el-form-item label="时间规则:" prop="timerule">
            <el-input placeholder="请输入" v-model="codeform.timerule"></el-input>
        </el-form-item>
        <el-form-item label="操作时间:" prop="timeRange">
            <el-date-picker v-model="codeform.timeRange" :value-format="dateFormat" type="datetimerange"
                range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="drawer = true">添加</el-button>
        <el-button type="danger" @click="DeleteAll">删除</el-button>
        <el-button @click="Export">导出</el-button>
    </div>
    <!--表格-->
    <el-table :data="codedata" stripe  style="margin-top: 10px;" @selection-change="SelectChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column fixed  type="index" label="序号" width="70px"></el-table-column>
        <el-table-column prop="code_name" label="目标表单"></el-table-column>
        <el-table-column prop="code_prefix" label="编号前缀"></el-table-column>
        <el-table-column prop="timerule" label="时间规则"></el-table-column>
        <el-table-column prop="code_num" label="流水号/位"></el-table-column>
        <el-table-column prop="code_step" label="步长"></el-table-column>
        <el-table-column prop="numberrule" label="编号生成规则"></el-table-column>
        <el-table-column prop="create_name" label="操作人"></el-table-column>
        <el-table-column prop="create_time" label="操作时间"></el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row.code_id)">编辑</el-button>
                <el-button type="danger" text="删除" @click="ShowDelete(scope.row.code_id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

    <!--添加抽屉-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">添加</h4>
        </template>
        <template #default>
            <el-form :model="addform" ref="addformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="目标表单" prop="name">
                    <el-input placeholder="请输入目标表单" v-model="addform.name" @input="ChangePrefix"></el-input>
                </el-form-item>
                <el-form-item label="编号前缀" prop="prefix">
                    <el-input placeholder="请输入编号前缀" v-model="addform.prefix" disabled></el-input>
                </el-form-item>
                <el-form-item label="时间规则" prop="timerule">
                    <el-checkbox-group v-model="addform.timerule">
                        <el-checkbox label="年YYYY" value="年"></el-checkbox>
                        <el-checkbox label="月MM" value="月"></el-checkbox>
                        <el-checkbox label="日DD" value="日"></el-checkbox>
                        <el-checkbox label="时HH" value="时"></el-checkbox>
                        <el-checkbox label="分MM" value="分"></el-checkbox>
                        <el-checkbox label="秒SS" value="秒"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="流水号/位" prop="num">
                    <el-input placeholder="请输入流水号/位" v-model="addform.num"></el-input>
                </el-form-item>
                <el-form-item label="步长" prop="step">
                    <el-input placeholder="请输入步长" v-model="addform.step"></el-input>
                </el-form-item>
                <el-form-item label="编号生成规则" prop="numberrule">
                    <el-input placeholder="请输入编号生成规则" v-model="addform.numberrule"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="Add">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--修改抽屉-->
    <el-drawer v-model="drawer2">
        <template #header>
            <h4 style="text-align: left;">修改</h4>
        </template>
        <template #default>
            <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="目标表单" prop="name">
                    <el-input placeholder="请输入目标表单" v-model="updateform.name" @input="ChangePrefix"></el-input>
                </el-form-item>
                <el-form-item label="编号前缀" prop="prefix">
                    <el-input placeholder="请输入编号前缀" v-model="updateform.prefix" disabled></el-input>
                </el-form-item>
                <el-form-item label="时间规则" prop="timerule">
                    <el-checkbox-group v-model="updateform.timerule">
                        <el-checkbox label="年YYYY" value="年"></el-checkbox>
                        <el-checkbox label="月MM" value="月"></el-checkbox>
                        <el-checkbox label="日DD" value="日"></el-checkbox>
                        <el-checkbox label="时HH" value="时"></el-checkbox>
                        <el-checkbox label="分MM" value="分"></el-checkbox>
                        <el-checkbox label="秒SS" value="秒"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="流水号/位" prop="num">
                    <el-input placeholder="请输入流水号/位" v-model="updateform.num"></el-input>
                </el-form-item>
                <el-form-item label="步长" prop="step">
                    <el-input placeholder="请输入步长" v-model="updateform.step"></el-input>
                </el-form-item>
                <el-form-item label="编号生成规则" prop="numberrule">
                    <el-input placeholder="请输入编号生成规则" v-model="updateform.numberrule"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer2 = false">取消</el-button>
                <el-button type="primary" @click="Update">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--删除模态框-->
    <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import http from '../auth/index';
import { ElMessage } from 'element-plus'; //提示信息
import pinyin from 'pinyin';
import * as XLSX from 'xlsx';
export default {
    setup() {
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //规则验证
        const rules = reactive({
            name: [
                { required: true, message: '请输入目标表单', trigger: 'blur' },
                { pattern: /^[^0-9]*$/, message: '目标表单不能输入数字', trigger: 'blur' }
            ],
            timerule: [
                { required: true, message: '请选择时间规则', trigger: 'blur' },
            ],
            num: [
                { required: true, message: '请输入流水号', trigger: 'blur' },
                { pattern: /^\d+$/, message: '只能是数字', trigger: 'blur' }
            ],
            step: [
                { required: true, message: '请输入步长', trigger: 'blur' },
                { pattern: /^\d+$/, message: '只能是数字', trigger: 'blur' }
            ],
            numberrule: [
                { required: true, message: '请输入', trigger: 'blur' },
            ],
        });
       
        //根据目标表单获取简拼
        function ChangePrefix() {
            if (addform.name) {
                // 使用 pinyin 库获取简拼
                const pyArray = pinyin(addform.name, {
                    style: pinyin.STYLE_FIRST_LETTER,
                    heteronym: false
                });
                // 将简拼数组转换为字符串
                addform.prefix = pyArray.map(item => item[0]).join('').toUpperCase();
            } else {
                addform.prefix = "";
            }
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "序号": row.code_id,
                "目标表单": row.code_name,
                "编号前缀": row.code_prefix,
                "时间规则": row.timerule,
                "流水号/位": row.code_num,
                "步长": row.code_step,
                "编号生成规则": row.numberrule,
                "操作人": row.create_name,
                "操作时间": row.create_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "编号规则");
            // 导出并下载
            XLSX.writeFile(wb, `编号规则${new Date().toLocaleDateString()}.xlsx`);
        }

        //当前codeid
        const codeid=ref(0);
        
        //#region 查询

        //表单
        const coderef = ref("");
        const codeform = reactive({
            name: "",
            prefix: "",
            timerule: "",
            timeRange: [null, null],
        })
        //表格数据
        const codedata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
         //日期格式
         const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function Reset() {
            coderef.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            All();
        }

        //查询数据
        function All() {
            http.get("/CodeRule/GetCodeRule", {
                params: {
                    name: codeform.name,
                    prefix: codeform.prefix,
                    timerule: codeform.timerule,
                    starttime: codeform.timeRange[0],
                    endtime: codeform.timeRange[1],
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                }));
                codedata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        //#endregion


        //#region 添加

        //添加抽屉
        const drawer = ref(false);

        const addformref = ref("");
        //添加表单
        const addform = reactive({
            name: "",
            prefix: "",
            timerule: [],
            num: "",
            step: "",
            numberrule: "",
            create_name: user.name,
            create_time: new Date(),
        })
       
         //添加
         function Add() {
            addformref.value.validate((valid) => {
                if (valid) {
                    //添加数据
                    const adddata = {
                        code_name: addform.name,
                        code_prefix: addform.prefix,
                        timerule: addform.timerule.join(''),
                        code_num: addform.num,
                        code_step: addform.step,
                        numberrule: addform.numberrule,
                        create_name: addform.create_name,
                        create_time: formatDateTime(addform.create_time),
                    }
                    http.post("/CodeRule/AddCodeRule",adddata)
                    .then(res => {
                        if (res.data> 0) {
                            ElMessage({
                                message: '添加成功.',
                                type: 'success',
                            })
                            All();
                            //清除表单
                            addformref.value?.resetFields();
                        }
                    }).catch(err => {
                        console.log(err);
                    })
                }
            })
        }
        

        //#endregion


        //#region 修改


        //修改抽屉
        const drawer2=ref(false);
        //修改表单
        const updateformref=ref("");
        const updateform = reactive({
            id:"",
            name: "",
            prefix: "",
            timerule: [],
            num: "",
            step: "",
            numberrule: "",
            update_name: user.name,
            update_time: new Date(),
        })
        //显示修改
        function ShowUpdate(id){
            drawer2.value=true;
            codeid.value=id;
            //根据当前id查询信息
            http.get("/CodeRule/GetCodeRuleByid?id="+id)
            .then(res=>{
                updateform.id=res.data.code_id;
                updateform.name=res.data.code_name;
                updateform.prefix=res.data.code_prefix;
                const timeruleStr = res.data.timerule;
                    if (timeruleStr) {
                        updateform.timerule = timeruleStr.split('').filter(item => 
                            ['年', '月', '日', '时', '分', '秒'].includes(item)
                        );
                    } else {
                        updateform.timerule = [];
                    }
                updateform.num=res.data.code_num;
                updateform.step=res.data.code_step;
                updateform.numberrule=res.data.numberrule;
            }).catch(err=>{
                console.log(err);
            })
        }
        //修改
        function Update(){
            //修改数据
            const updatedata ={
                code_id:updateform.id,
                code_name: updateform.name,
                code_prefix: updateform.prefix,
                timerule: updateform.timerule.join(''),
                code_num: updateform.num,
                code_step: updateform.step,
                numberrule: updateform.numberrule,
                update_name: updateform.update_name,
                update_time: formatDateTime(updateform.update_time),
            }
            http.put("/CodeRule/UpdateCodeRule",updatedata)
            .then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '修改成功.',
                        type: 'success',
                    })
                    All();
                }
            }).catch(err=>{
                console.log(err);
            })
        }


        //#endregion


        //#region 删除

            //删除模态框
            const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(id){
                codeid.value=id;
                DeleteialogVisible.value=true;
            }
            function Delete(){
                http.put("/CodeRule/DeleteCodeRule?id="+codeid.value)
                .then(res=>{
                    if(res.data>0){
                        ElMessage({
                            message: '删除成功.',
                            type: 'success',
                        })
                        All();
                        DeleteialogVisible.value=false;
                    }else{
                        ElMessage.error('删除失败.')
                    }
                }).catch(err=>{
                    console.log(err);
                })
            }
            //批量删除
            function DeleteAll(){
                if(selectdata.value.length==0){
                    ElMessage({
                        message: '请选择要删除的数据.',
                        type: 'warning',
                    })
                    return;
                }
                //循环删除
                selectdata.value.forEach(item => {
                    http.put("/CodeRule/DeleteCodeRule?id="+item.code_id)
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '删除成功.',
                                type: 'success',
                            })
                            All();
                            DeleteialogVisible.value=false;
                        }else{
                            ElMessage.error('删除失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                });
            }


        //#endregion


        //挂载
        onMounted(() => {
            All();
        });


        return {
            codeform,
            coderef,
            dateFormat,
            Reset,
            Search,
            codedata,
            formatDateTime,
            rows,
            handlePageChange,
            drawer,
            user,
            addform,
            addformref,
            rules,
            ChangePrefix,
            Add,
            DeleteialogVisible,
            ShowDelete,
            codeid,
            Delete,
            SelectChange,
            DeleteAll,
            Export,
            ShowUpdate,
            drawer2,
            updateform,
            updateformref,
            Update
        }
    }
}
</script>

<style scoped></style>